package json_xml;

import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.PropertyUtils;

import net.sf.json.JSONObject;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;
import com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver;
import com.thoughtworks.xstream.io.json.JsonWriter;

public class JsonUtil {

	public static Object getObj(String json,Class<?> clazz) {
		XStream xstream = new XStream(new JettisonMappedXmlDriver());
		xstream.setMode(XStream.NO_REFERENCES);
		String className = clazz.getName();
		json = "{\"" + className + "\":" + json + "}";
		return xstream.fromXML(json);
	}

	public static String getJson(Object obj,String displayName) {
		XStream xstream = new XStream(new JsonHierarchicalStreamDriver() {
			public HierarchicalStreamWriter createWriter(Writer writer) {
				return new JsonWriter(writer, JsonWriter.DROP_ROOT_MODE);
			}
		});
		xstream.setMode(XStream.NO_REFERENCES);
		//xstream.alias(displayName, obj.getClass());
		String json = xstream.toXML(obj).replaceAll(" |\n", "");
		return json;
	}

	public static void main(String[] a) throws IOException {
		Man man = new Man();

		man.setAge(23);
		man.setName("mike");
		man.setBoys(new String[] { "boy1", "boy2" });

		List<String> list = new ArrayList<String>();
		list.add("girl1");
		list.add("girl2");
		man.setGirls(list);

		Map<String,String> map = new HashMap<String,String>();
		map.put("email1", "mike@sina.com");
		map.put("email2", "mike@163.com");
		man.setEmails(map);

		man.setSs(new String[][]{{"aa","bb"},{"cc","dd"}});

		Woman woman = new Woman();
		woman.setName("lily");
		Woman woman2 = new Woman();
		woman2.setName("zhenhuan");
		List<Addr> addrs = new ArrayList<Addr>();
		Addr ad = new Addr();
		ad.setAd("ad");
		addrs.add(ad);
		woman2.setAddrs(addrs);
		Person perso = new Person();
		perso.setAge(11);
		woman2.setPer(perso);
		man.setMyWoman(woman2);
		
		List<Woman> weman = new ArrayList<Woman>();
		weman.add(woman);
		weman.add(woman2);
		man.setWeman(weman);

		JSONObject o = JSONObject.fromObject(man);
		System.out.println(o);
		
		JSONObject s = JSONObject.fromObject(o.toString());
		Map mapclass = new HashMap();
		mapclass.put("weman", Woman.class);
		mapclass.put("addrs", Addr.class);
		Man mike = (Man) JSONObject.toBean(s, Man.class, mapclass );
		System.out.println(mike.getName());
		System.out.println(mike.getGirls().get(0));
		System.out.println(mike.getEmails().get("email1"));
		System.out.println(mike.getMyWoman().getName());
		System.out.println(mike.getMyWoman().getAddrs().get(0).getAd());
		System.out.println(mike.getMyWoman().getPer().getAge());
		System.out.println(mike.getWeman().get(0).getName());
		org.apache.commons.beanutils.PropertyUtils sss = new PropertyUtils();
	}
}
